package com.hfzy.ihk.web.linkcall.context.impl;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.web.linkcall.context.ContextIntf;
import com.hfzy.ihk.web.linkcall.context.ContextKey;
import org.springframework.stereotype.Component;

@Component
public class WebContextIntfImpl implements ContextIntf {

	private static ThreadLocal<HttpServletRequest> request = new ThreadLocal<HttpServletRequest>();
	private static ThreadLocal<HttpServletResponse> response = new ThreadLocal<HttpServletResponse>();

	public Object get(ContextKey key) {
		if (key == ContextKey.CLIENT_IP)
			return Utils.getIp(getRequest());
		else if (key == ContextKey.CLIENT_HOST)
			return getRequest().getRemoteHost();
		return getSession()==null?null:getSession().getAttribute(key.name());
	}

	private HttpSession getSession() {
		return getRequest()==null?null:getRequest().getSession();
	}

	@Override
	public HttpServletRequest getRequest() {

		return request.get()==null?null:request.get();
	}

	@Override
	public void setRequest(HttpServletRequest req) {
		request.set(req);
	}

	public HttpServletResponse getResponse() {
		return response.get();
	}

	public void setRequestResponse(HttpServletRequest req,
								   HttpServletResponse resp) {
		request.set(req);
		response.set(resp);
	}

	public void sendRedirect(String url) {
		try {
			getResponse().sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String getContextPath() {
		return getRequest().getContextPath();
	}

	public void set(ContextKey key, Object obj) {
		getSession().setAttribute(key.name(), obj);
	}

	public void remove(ContextKey key) {
		getSession().removeAttribute(key.name());
	}

	public void clearAll() {
		for (ContextKey key : ContextKey.values()) {
			remove(key);
		}
	}

	public String getURL(String relativePath) {
		HttpServletRequest req = getRequest();
		return "http://" + req.getServerName() + ":" + req.getServerPort()
				+ req.getContextPath() + "/" + relativePath;
	}

}
